package com.humble.vichatbackend.web_socket;


import jakarta.websocket.RemoteEndpoint;
import jakarta.websocket.Session;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

@Slf4j
@Data
public class ChatSocket {
    public final Map<Long, Session> ONLINE_USER_MAP = new ConcurrentHashMap<>();

    private final Map<Long, List<String>> LEAVE_MESSAGE_MAP = new ConcurrentHashMap<>();

    private final Set<Long> TEAM_USERID = new ConcurrentSkipListSet<>();

    //todo 返回时携带队伍信息用于前端过滤（仅显示）
    public void sendMessage(Long sourceId,Long targetId,String message){
        Session session = ONLINE_USER_MAP.get(targetId);
        if(session != null){
            RemoteEndpoint.Basic basic = session.getBasicRemote();
            try {
                //todo 优化成获取具体用户名字
                basic.sendText(sourceId+":"+message);
            } catch (IOException e) {
                log.error("发送消息出现异常");
            }
        }
        else {
            if(!TEAM_USERID.contains(targetId))return;
            //小队存在该人则发出留言
            List<String> strings = LEAVE_MESSAGE_MAP.get(targetId);
            if(strings == null){
                strings = new ArrayList<String>();
                strings.add(message);
                LEAVE_MESSAGE_MAP.put(targetId, strings);
            }
            strings.add(message);
        }
    }

    public void sendToAll(Long sourceId,String message){
        TEAM_USERID.forEach(id->sendMessage(sourceId,id,message));
    }

    public void sendLeaveMessage(Long id){
        Session session = ONLINE_USER_MAP.get(id);
        List<String> strings = LEAVE_MESSAGE_MAP.get(id);
        if(strings!=null&&!strings.isEmpty()){
            RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
            for (String message : strings) {
                asyncRemote.sendText(message);
            }
        }
    }
}
